package csc309;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.GregorianCalendar;

public class Flight {

	String from, to;
	int seats;
	long time;

	public Flight(String from, String to, int day, int month, int year, int time) {

		this.from = from;
		this.to = to;
		this.time = (new GregorianCalendar(year, month, day, time, 0))
				.getTimeInMillis();
		getSeatsFromFile();
	}
	
	public Flight(String s) {
		String[] sArray = s.trim().split(".");

		this.from = sArray[0];
		this.to = sArray[1];
		this.time = Long.parseLong(sArray[2]);
		getSeatsFromFile();
		// this.seats = Integer.parseInt(sArray[3]);
	}
	
	public int getSeats() {
		return this.seats;
	}

	public boolean isSeatTaken(int seatNum) {
		return (seats & (1 << (seatNum - 1))) != 0;
	}

	public void takeSeat(int seatNum) {
		seats |= 1 << (seatNum - 1);
		writeToFile();
	}

	public boolean equals(Flight f) {
		return from.equals(f.from) && to.equals(f.to) && f.time == time;
	}

	private void getSeatsFromFile() {
		try {
			FileInputStream fs = new FileInputStream(getFileName());
			DataInputStream in = new DataInputStream(fs);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String data = br.readLine();
			in.close();
			seats = Integer.parseInt(data.trim());
		} catch (Exception e) {
			seats = 0;
		}
	}

	public void writeToFile() {
		try {
			FileWriter fw = new FileWriter(getFileName());
			BufferedWriter out = new BufferedWriter(fw);
			out.write(((Integer) seats).toString());
			out.close();
		} catch (Exception e) {
		}
	}

	public String getFileName() {
		// return System.getProperty("java.io.tmpdir") + toString() + ".txt";
		return toString() + ".txt";
	}

	public String toString() {
		return from + "." + to + "." + time;
	}
}
